package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.mapper.UserMapper;
import com.example.reggie.entity.User;
import com.example.reggie.service.UserService;
import com.example.reggie.utils.R;
import com.example.reggie.utils.ValidateCodeUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void sendMsg(String phone) {
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        stringRedisTemplate.opsForValue().set("user:code:"+phone,code);
        System.out.println(code);
    }

    @Override
    public R login(Map map, HttpSession session) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        String checkCode = stringRedisTemplate.opsForValue().get("user:code:" + phone);
        if (checkCode == null || checkCode == ""){
            return R.error("手机号错误");
        }
        if (!phone.isEmpty() && !code.isEmpty()){
            if (code.equals(checkCode)){
                LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper();
                lqw.eq(User::getPhone,phone);
                User one = getOne(lqw);
                if (one == null){
                    one = new User();
                    one.setPhone(phone);
                    one.setStatus(1);
                    save(one);
                }
                System.out.println(one.getId());
                session.setAttribute("user",one.getId());
                return R.success(one);
            }
            return R.error("验证码错误");
        }
        return R.error("手机号错误");
    }
}
